<template>
    <el-form :model="form" ref="formRef" label-width="120px" style="padding: 20px;">
        <!-- 表单头部 -->
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="入库单号">
                    <el-input v-model="form.inboundNum" placeholder="可不填写，自动生成"></el-input>
                </el-form-item>
                <el-form-item label="供应商编号" required>
                    <el-input v-model="form.supplierID"></el-input>
                </el-form-item>
                <el-form-item label="供应商联系方式" required>
                    <el-input v-model="form.supplierPhone"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="form.rember" :maxlength="300" placeholder="请输入备注信息"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="入库单类型" prop="storage" required>
                    <el-select v-model.number="form.storage" placeholder="请选择入库类型">
                        <el-option label="原材料入库" value="101"></el-option>
                        <el-option label="成品入库" value="102"></el-option>
                        <el-option label="销售退货入库" value="103"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="供应商名称" prop="supplierName" required>
                    <el-input v-model="form.supplierName"></el-input>
                </el-form-item>
                <el-form-item label="制单人">
                    <el-input v-model="form.creator" disabled></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="关联订单号" prop="associatedNum">
                    <el-input v-model="form.associatedNum"></el-input>
                </el-form-item>
                <el-form-item label="供应商联系人" prop="supplierPeople">
                    <el-input v-model="form.supplierPeople"></el-input>
                </el-form-item>
                <el-form-item label="制单时间">
                    <el-input v-model="form.outAuditTime" disabled></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <div>
            <el-button type="primary" size="small" icon="el-icon-plus" @click="centerDialogVisible = true"
                style="float: right; margin-bottom: 10px;">新增产品</el-button>
        </div>
        <!-- 产品表格 -->
        <el-table :data="products" style="margin-top: 20px;" border>
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column label="产品名称" prop="productName"></el-table-column>
            <el-table-column label="产品编码" prop="productId"></el-table-column>
            <el-table-column label="规格" prop="specification"></el-table-column>
            <el-table-column label="批次">
                <template #default="{ row }">
                    <el-input v-model="row.batch" size="small" placeholder="请输入批次"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="单价">
                <template #default="{ row }">
                    <el-input v-model.number="row.price" size="small" type="number"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="入库数量">
                <template #default="{ row }">
                    <el-input v-model.number="row.quantity" size="small" type="number"
                        @input="calculateTotal(row)"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="总价" width="100">
                <template #default="{ row }">
                    <span :style="row.totalPrice < 0 || isNaN(row.totalPrice) ? 'color: red' : ''">
                        {{ row.totalPrice ? row.totalPrice.toFixed(2) : '0.00' }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="库位">
                <template #default="{ row }">
                    <el-input v-model="row.location" size="small" placeholder="请输入库位"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
                <template #default="{ row }">
                    <el-button size="small" icon="el-icon-edit" @click="deleteProduct(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px;">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm" style="margin-left: 10px;">取消</el-button>
        </div>
    </el-form>

    <el-dialog v-model="centerDialogVisible" title="选择产品" style="width: 1300px;height: 900px;" center>
        <span>
            <div class="search-container">
                <el-input v-model="from.ProductId" placeholder="请输入产品编号" clearable :disabled="loading" />
                <el-input v-model="from.ProductName" placeholder="请输入产品名称" clearable :disabled="loading" />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </div>
            <el-table :data="productsData" style="width: 100%;" border row-key="productId" ref="productTableRef">
                <el-table-column type="selection" />
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="productId" label="产品ID"></el-table-column>
                <el-table-column prop="productName" label="产品名称"></el-table-column>
                <el-table-column prop="category" label="类别"></el-table-column>
                <el-table-column prop="specification" label="规格"></el-table-column>
                <el-table-column prop="price" label="单价"></el-table-column>
            </el-table>
            <el-pagination v-show="from.totalPage > 1" :current-page="from.PageIdex" :page-sizes="[4, 8, 12]"
                :total="from.totalCount" @size-change="handlePageSizeChange" @current-change="handleCurrentChange" />
        </span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addSelectedProducts">添加</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from "@/stores/counter";

const router = useRouter();
const route = useRoute();
const Store = useCounterStore();
const id = route.query.id;

// 表单数据
const form = reactive({
    "pid": 0,
    "inboundNum": Math.floor(Math.random() * (999 - 100 + 1)) + 100,
    "associatedNum": "",
    "batch": "",
    "specifications": "",
    "quantity": 0,
    "totalprice": 0,
    "location": "",
    "storage": 101,
    "supplier": "",
    "supplierID": "",
    "supplierName": "",
    "supplierPeople": "",
    "supplierPhone": "",
    "creator": Store.user?.userName || '未知用户',
    "reviewer": "",
    "outAuditTime": new Date().toISOString(),
    "outAuditstatus": 101,
    "outCreationTime": new Date().toISOString(),
    "rember": "",
    "shenRember": ""
});

// 计算总价
const calculateTotal = (row) => {
    const price = parseFloat(row.price);
    const quantity = parseFloat(row.quantity);
    row.price = isNaN(price) ? 0 : price;
    row.quantity = isNaN(quantity) ? 0 : quantity;
    row.totalPrice = row.price * row.quantity;
};

// 修改表单
const submitForm = () => {
    const submitData = {
        id: parseInt(id),
        pid: String(products.value.reduce((acc, row) => acc + row.productId, 0)),
        inboundNum: String(form.inboundNum),
        associatedNum: form.associatedNum,
        batch: products.value.map(row => row.batch).join(','),
        specifications: products.value.map(row => row.specification).join(','),
        quantity: String(products.value.reduce((acc, row) => acc + row.quantity, 0)),
        totalprice: String(products.value.reduce((acc, row) => acc + row.totalPrice, 0)),
        location: products.value.map(row => row.location).join(','),
        storage: parseInt(form.storage),
        supplier: "无",
        supplierID: form.supplierID,
        supplierName: form.supplierName,
        supplierPeople: form.supplierPeople,
        supplierPhone: form.supplierPhone,
        creator: Store.user?.userName || '未知用户',
        reviewer: "无",
        outAuditTime: new Date().toISOString(),
        outAuditstatus: 101,
        outCreationTime: new Date().toISOString(),
        rember: "无",
        isDelete: 0,
        shenRember: "无"
    };
    console.log(submitData);
    axios.put('https://localhost:44351/api/Store/Handle', submitData)
        .then((res) => {
            if (res.data.code === 206) {
                ElMessage.success('修改成功');
                router.push('/StoreShow');
            } else {
                ElMessage.error('修改失败');
            }
        })
        .catch((error) => {
            ElMessage.error(`请求出错：${error.message}`);
        });
};

const centerDialogVisible = ref(false);
const from = reactive({
    ProductId: '',
    ProductName: '',
    PageIdex: 1,
    PageSize: 15,
    totalPage: 0,
    totalCount: 0
});

const productsData = ref([]);
const loading = ref(false);
const productTableRef = ref(null);

const Moks = () => {
    loading.value = true;
    axios.get("http://localhost:5178/api/Product/ProductQuser", {
        params: {
            ProductId: from.ProductId,
            ProductName: from.ProductName,
            PageIdex: from.PageIdex,
            PageSize: from.PageSize,
        }
    }).then((res) => {
        console.log(res.data.data.list)
        productsData.value = res.data.data.list;
        from.totalCount = res.data.data.totalCount;
        from.totalPage = res.data.data.totalPage;
    }).finally(() => {
        loading.value = false;
    });
};

const handlePageSizeChange = (size) => {
    from.PageSize = size;
    from.PageIdex = 1;
    Moks();
};

const handleCurrentChange = (page) => {
    from.PageIdex = page;
    Moks();
};

const handleSearch = () => {
    from.PageIdex = 1;
    Moks();
};

const addSelectedProducts = async () => {
    console.log('开始添加产品');
    if (!productTableRef.value) {
        ElMessage.error("请先搜索产品");
        return;
    }

    const selectedRows = productTableRef.value.getSelectionRows();
    if (selectedRows.length === 0) {
        ElMessage.warning("请至少选择一个产品");
        return;
    }

    const selectedIds = selectedRows.map(row => row.productId);
    console.log('选中的产品ID:', selectedIds);

    try {
        const res = await axios.get("http://localhost:5178/api/Product/ProductModelPhto", {
            params: { ProductId: selectedIds },
            paramsSerializer: (params) => {
                return Object.entries(params).flatMap(([key, value]) => {
                    if (Array.isArray(value)) {
                        return value.map(v => `${key}=${encodeURIComponent(v)}`);
                    }
                    return `${key}=${encodeURIComponent(value)}`;
                }).join('&');
            }
        });

        if (res.data.code === 210 && res.data.data) {
            // 把新获取的产品和原有的产品进行合并，防止原有数据被覆盖
            const newProducts = res.data.data.map(product => ({
                productId: product.productId,
                productName: product.productName,
                specification: product.specification,
                price: parseFloat(product.price) || 0,
                quantity: 0,
                totalPrice: 0,
                batch: product.batch || '',
                location: product.location || ''
            }));
            // 先过滤掉已存在的产品ID，避免重复
            const filteredNewProducts = newProducts.filter(newProduct =>
                !products.value.some(existingProduct => existingProduct.productId === newProduct.productId)
            );
            // 合并数组
            products.value = [...products.value, ...filteredNewProducts];
            console.log('更新后的产品数据:', products.value);
            nextTick(() => {
                products.value = [...products.value]; // 强制更新视图
            });
            centerDialogVisible.value = false; // 关闭对话框
            ElMessage.success('产品添加成功');
        } else {
            ElMessage.error(`获取产品数据失败：${res.data.msg}`);
        }
    } catch (error) {
        ElMessage.error('网络请求失败，请检查连接');
        console.error('接口错误:', error);
    }
};

const products = ref([]);

// 获取产品详细信息
const folieShow = (selectedIds) => {
    return new Promise((resolve, reject) => {
        axios.get("http://localhost:5178/api/Product/ProductModelPhto", {
            params: {
                ProductId: selectedIds
            },
            paramsSerializer: (params) => {
                return Object.entries(params).flatMap(([key, value]) => {
                    if (Array.isArray(value)) {
                        return value.map(v => `${key}=${encodeURIComponent(v)}`);
                    }
                    return `${key}=${encodeURIComponent(value)}`;
                }).join('&');
            }
        })
            .then((res) => {
                console.log('接口返回数据:', res.data);
                if (res.data.code === 200 && res.data.data) {
                    products.value = res.data.data.map(product => ({
                        productId: product.productId,
                        productName: product.productName,
                        specification: product.specification,
                        price: parseFloat(product.price) || 0,
                        quantity: 0,
                        totalPrice: 0,
                        batch: product.batch || '',
                        location: product.location || ''
                    }));
                    console.log('更新后的products:', products.value);
                    nextTick(() => {
                        products.value = [...products.value];
                    });
                }
                resolve();
            })
            .catch((error) => {
                console.error('接口错误:', error);
                reject(error);
            });
    });
};

// 取消表单操作
const cancelForm = () => {
    Object.keys(form).forEach(key => form[key] = '');
    products.value = [];
};

// 自动生成入库单号
onMounted(() => {
    if (id) {
        ShWorker();
        Moks();
    } else {
        const generateInboundNumber = async () => {
            try {
                const response = await axios.get('http://localhost:5178/api/inbound-orders/generate-number');
                form.inboundNum = response.data;
            } catch (error) {
                ElMessage.error('生成入库单号失败');
            }
        };
        generateInboundNumber();
        Moks();
    }
});

const deleteProduct = (row) => {
    products.value = products.value.filter(item => item.productId !== row.productId);
    ElMessage.success('产品删除成功');
};

// 反填显示
const ShWorker = () => {
    axios.get(`http://localhost:5178/api/Store/StoreOnly?Id=${id}`).then((res) => {

        if (res.data && res.data.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
            const item = res.data.data[0];
            Object.assign(form, item);

            products.value = res.data.data.map(product => ({
                productId: product.productId,
                productName: product.productName,
                specification: product.specification,
                price: parseFloat(product.price) || 0,
                quantity: parseFloat(product.quantity) || 0,
                totalPrice: parseFloat(product.totalprice) || 0,
                batch: product.batch || '',
                location: product.location || ''
            }));

            console.log('反填后的产品数据:', products.value);
            nextTick(() => {
                products.value = [...products.value]; // 强制更新视图
            });
        }
    }).catch((error) => {
        ElMessage.error(`获取表单数据失败：${error.message}`);
    });
};

const handleClose = (done) => {
    ElMessageBox.confirm('确定要关闭吗？')
        .then(() => {
            done();
        })
        .catch(() => {
            centerDialogVisible.value = true;
        });
};
</script>

<style scoped>
.el-table {
    width: 100%;
}

.search-container {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

.search-container .el-input {
    flex: 1;
    max-width: 200px;
}
</style>